#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Tk界面模块
提供四足机器人轨迹规划程序的图形用户界面
"""

import numpy as np
import tkinter as tk
from tkinter import ttk, messagebox

# 导入配置
from config import LEG_NAMES, LEG_PARAMS, MOVEMENT_SPEED

class TkInterface:
    """Tk界面类，提供用户界面"""
    
    def __init__(self, robot, planner, visualizer):
        """初始化Tk界面
        
        参数:
            robot: FourLeggedRobot实例
            planner: TrajectoryPlanner实例
            visualizer: TrajectoryVisualizer实例
        """
        self.robot = robot
        self.planner = planner
        self.visualizer = visualizer
        self.current_angles = {}
        
        # 为每条腿初始化当前角度
        for leg_id in robot.leg_chains.keys():
            self.current_angles[leg_id] = np.zeros(len(robot.leg_chains[leg_id].links))
        
        # 创建主窗口
        self.root = tk.Tk()
        self.root.title("四足机器人轨迹规划控制面板")
        self.root.geometry("800x600")
        
        # 创建控制变量
        self.create_control_variables()
        
        # 创建界面组件
        self.create_widgets()
        
        # 绑定关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
    
    def create_control_variables(self):
        """创建控制变量"""
        # 全局控制变量
        self.running_var = tk.BooleanVar(value=False)
        
        # 腿部参数变量
        self.leg_vars = {}
        
        for leg_id, params in LEG_PARAMS.items():
            self.leg_vars[leg_id] = {
                "center_x": tk.DoubleVar(value=params["center_x"]),
                "center_y": tk.DoubleVar(value=params["center_y"]),
                "base_z": tk.DoubleVar(value=params["base_z"]),
                "long_axis": tk.DoubleVar(value=params["long_axis"]),
                "short_axis": tk.DoubleVar(value=params["short_axis"]),
                "height": tk.DoubleVar(value=params["height"])
            }
    
    def create_widgets(self):
        """创建界面组件"""
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建全局控制区域
        global_frame = ttk.LabelFrame(main_frame, text="全局控制", padding="5")
        global_frame.pack(fill=tk.X, pady=5)
        
        # 启动/停止按钮
        ttk.Checkbutton(
            global_frame, 
            text="启动/停止", 
            variable=self.running_var,
            command=self.toggle_running
        ).grid(row=0, column=0, padx=5, pady=5)
        

        
        # 重置按钮
        ttk.Button(
            global_frame,
            text="重置参数",
            command=self.reset_params
        ).grid(row=0, column=3, padx=5, pady=5)
        
        # 创建腿部控制区域
        legs_frame = ttk.Frame(main_frame)
        legs_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 为每条腿创建控制面板
        for i, (leg_id, leg_name) in enumerate(LEG_NAMES.items()):
            row, col = divmod(i, 2)
            self.create_leg_control(legs_frame, leg_id, leg_name, row, col)
    
    def create_leg_control(self, parent, leg_id, leg_name, row, col):
        """创建腿部控制面板
        
        参数:
            parent: 父容器
            leg_id: 腿的ID
            leg_name: 腿的名称
            row: 行索引
            col: 列索引
        """
        # 创建腿部框架
        leg_frame = ttk.LabelFrame(parent, text=f"{leg_name} ({leg_id})", padding="5")
        leg_frame.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
        
        # 设置网格权重
        parent.grid_columnconfigure(0, weight=1)
        parent.grid_columnconfigure(1, weight=1)
        parent.grid_rowconfigure(0, weight=1)
        parent.grid_rowconfigure(1, weight=1)
        
        # 参数标签和输入框
        params = [
            ("中心X:", "center_x", -0.5, 0.5),
            ("中心Y:", "center_y", -0.5, 0.5),
            ("基础Z:", "base_z", -0.5, 0.0),
            ("长半轴:", "long_axis", 0.0, 0.2),
            ("短半轴:", "short_axis", 0.0, 0.2),
            ("高度:", "height", 0.0, 0.1)
        ]
        
        for i, (label_text, param_name, min_val, max_val) in enumerate(params):
            ttk.Label(leg_frame, text=label_text).grid(row=i, column=0, sticky="w", padx=5, pady=2)
            
            # 创建输入框和滑块组合
            param_frame = ttk.Frame(leg_frame)
            param_frame.grid(row=i, column=1, sticky="ew", padx=5, pady=2)
            
            # 输入框
            entry = ttk.Entry(
                param_frame,
                textvariable=self.leg_vars[leg_id][param_name],
                width=8
            )
            entry.pack(side=tk.LEFT)
            
            # 滑块
            scale = ttk.Scale(
                param_frame,
                from_=min_val,
                to=max_val,
                orient=tk.HORIZONTAL,
                variable=self.leg_vars[leg_id][param_name],
                length=150
            )
            scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
    
    def update_planner_params(self):
        """更新规划器参数"""
        for leg_id, vars_dict in self.leg_vars.items():
            for param_name, var in vars_dict.items():
                self.planner.current_params[leg_id][param_name] = var.get()
    
    def toggle_running(self):
        """切换运行状态"""
        global running
        running = self.running_var.get()
    
    def reset_params(self):
        """重置参数到默认值"""
        # 重置规划器参数
        for leg_id, params in LEG_PARAMS.items():
            self.planner.current_params[leg_id] = params.copy()
        
        # 更新界面变量
        for leg_id, params in LEG_PARAMS.items():
            for param_name, value in params.items():
                if param_name in self.leg_vars[leg_id]:
                    self.leg_vars[leg_id][param_name].set(value)
    
    def update_ui(self):
        """更新界面"""
        # 在这里可以添加界面更新逻辑
        pass
    
    def on_closing(self):
        """关闭窗口处理"""
        global running
        running = False
        self.root.destroy()
    
    def start(self):
        """启动界面"""
        # 启动主循环
        self.root.mainloop()
